﻿namespace HostedServiceDemo1
{
    public class HostedService1 : BackgroundService
    {

        #region 使用Scoped和Transient服务的问题
        /**
         * 单例中使用范围和瞬态服务会报错,因为单例一直存在范围和瞬态再什么时候销毁单例就取不到了
         * HostedServiceDemo1.HostedService1属于单例服务,无法使用HostedServiceDemo1.TestService类型服务,因为该服务类型为Scope
         * System.AggregateException:“Some services are not able to be constructed (Error while validating the service descriptor
         * 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: HostedServiceDemo1.HostedService1':
         * Cannot consume scoped service 'HostedServiceDemo1.TestService' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.)”
         * 
         */

        //private readonly TestService service;

        //public HostedService1(TestService service)
        //{
        //    this.service = service;
        //}
        #endregion


        private readonly IServiceScopeFactory serviceScopeFactory;

        private IServiceScope serviceScope;

        public HostedService1(IServiceScopeFactory serviceScopeFactory)
        {
            this.serviceScopeFactory = serviceScopeFactory;
            this.serviceScope = serviceScopeFactory.CreateScope();
        }


        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {

                TestService service = serviceScope.ServiceProvider.GetRequiredService<TestService>();

                while (!stoppingToken.IsCancellationRequested)
                {
                    Console.WriteLine("HostedService1启动" + service.Add(1, 1));

                    await Task.Delay(3000);//异步方法里不要用Thread.Sleep

                    string txt = await File.ReadAllTextAsync("d:/1.txt");

                    Console.WriteLine("文件读取完成");

                    //发生异常服务停止:所以我们要try...cactch包起来
                    //info: Microsoft.Hosting.Lifetime[0]
                    //Application is shutting down...
                    //string s = null;
                    //s.ToString(); //发生异常

                    await Task.Delay(3000);

                    Console.WriteLine(txt);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("服务中心出现未处理异常:" + ex);
            }

        }

        //BackgroundService:实现了IDisposable
        public override void Dispose()
        {
            //在HostedService1释放的时候也释放自己创建的IServiceScope
            //这样serviceScope的声明周期就和HostedService1生命周期一样了
            this.serviceScope.Dispose();
            base.Dispose();
        }

    }
}
